import { useState } from "react"
import { Button, Space, message } from "antd"
import { useDispatch } from 'react-redux'

import * as apis from "../../apis/user"
import { queryUsersAction } from '../../store/actions/userActions'

import useCURD from "../../hooks/useCURD"
import CommonModalForm from "../../components/common/CommonModalForm"
import CommonTable, { createColumn } from "../../components/common/CommonTable"
import CommonTotalAction from "../../components/common/CommonTotalAction"
import CommonFilterItem from "../../components/common/CommonFilterItem"
import useRowSelection from "../../hooks/useRowSelection"



const IdmUser = () => {
  const dispatch = useDispatch()

  const {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection
  } = useRowSelection({
    disabledKeys: ['admin', 'rest-admin']
  })

  const {
    listData,
    loading,
    handleCreate,
    handleModify,
    handleCancelForm,
    query,
    changeQueryValues,
    handleSubmit,
    formVisible,
    formTitle,
    formData,
    handleDeleteBatch
  } = useCURD({
    apis,
    moduleName: '用户',
    changeListSuccessCallBack: () => {
      dispatch(queryUsersAction())
    }
  })

  const columns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户id',
      width: 100,
      sorter: true
    },
    createColumn.searchResult({
      dataIndex: 'fullName',
      title: '名称',
      width: 200,
      searchWord: query.filter
    }),
    {
      key: 'email',
      dataIndex: 'email',
      title: '邮箱',
      sorter: true
    },
    {
      key: 'tenantId',
      dataIndex: 'tenantId',
      title: '租户',
      width: 120
    },
    {
      key: 'action',
      title: '操作',
      width: 200,
      align: 'center',
      render: (rowData) => {
        return <Space>
          <Button
            size="small"
            type="primary"
            onClick={() => { handleModify(rowData) }}
            disabled={rowData.id === 'admin' || rowData.id === 'rest-admin'}
          >修改详细信息</Button>
        </Space>
      }
    }
  ]

  const formItems = [
    {
      name: 'id',
      label: '用户id',
      required: true,
      hide: () => !formData.id
    },
    {
      name: 'email',
      required: true,
      label: '邮箱',
      rules: [{ type: 'email' }]
    },
    {
      name: 'password',
      label: '密码',
      type: 'password',
      required: true,
      hide: () => !formData.id
    },
    {
      name: 'firstName',
      required: true,
      label: '名'
    },
    {
      name: 'lastName',
      required: true,
      label: '姓'
    },
    {
      name: 'tenantId',
      label: '租户'
    }
  ]

  const changePasswordFormItems = [
    {
      name: 'password',
      label: '新密码',
      required: true
    },
    {
      name: 'repassword',
      label: '重复密码',
      required: true,
      rules: [
        ({ getFieldValue }) => ({
          validator(_, value) {
            if (!value || getFieldValue('password') === value) {
              return Promise.resolve();
            }
            return Promise.reject(new Error('两次密码输入不一致'));
          },
        }),
      ]
    }
  ]

  const handleTotalAction = (key) => {
    switch (key) {
      case 'password':
        setFormVisiblePassword(true)
        break
      case 'delete':
        handleDeleteBatch(selectedRowKeys, ()=>{
          setSelectedRowKeys([])
        })
        break
    }
  }

  const handleChangeTable = (pagination, filters, sorter) => {
    const obj = {
      'ascend': 'Asc',
      'descend': 'Desc'
    }
    if (sorter.order) {
      changeQueryValues({
        sort: `${sorter.field}${obj[sorter.order]}`
      })
    } else {
      changeQueryValues({
        sort: undefined
      })
    }
  }

  const [formVisiblePassword, setFormVisiblePassword] = useState(false)
  const handleSubmitPassword = async (values) => {
    try {
      await apis.changePassword({
        password: values.password,
        users: selectedRowKeys
      })
      message.success('密码修改成功')
      setFormVisiblePassword(false)
    } catch (error) {
      message.success('密码修改失败')
      setFormVisiblePassword(false)
    }
  }

  return <div className="page-wrap">
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      initValues={formData}
      formItems={formItems}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
    ></CommonModalForm>
    <CommonModalForm
      title="修改密码"
      visible={formVisiblePassword}
      formItems={changePasswordFormItems}
      onCancel={() => { setFormVisiblePassword(false) }}
      onSubmit={handleSubmitPassword}
    ></CommonModalForm>
    <div className="page-head">
      <Space>
        <Button type="primary" onClick={handleCreate}>创建用户</Button>
        <CommonTotalAction
          btns={[
            { key: 'password', name: '修改密码' },
            { key: 'delete', name: '删除' }
          ]}
          selectedRowKeys={selectedRowKeys}
          onAction={handleTotalAction}
          onCancel={() => { setSelectedRowKeys([]) }}
        ></CommonTotalAction>
      </Space>
      <Space>
        <CommonFilterItem.Search
          label="名称"
          field="filter"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
        ></CommonFilterItem.Search>
      </Space>
    </div>
    <div className="page-body">
      <CommonTable
        rowSelection={rowSelection}
        dataSource={listData}
        columns={columns}
        loading={loading}
        onChange={handleChangeTable}
      ></CommonTable>
    </div>
  </div>
}

export default IdmUser